using Android.App;
using Android.Content;
using Android.OS;
using AndroidX.Core.App;
using System.Timers;

namespace AndroidApp2
{

    /// <summary>
    /// 前台服务类 - 提供持续运行的后台服务功能
    /// 该服务会在状态栏显示持续通知，确保系统不会随意杀死服务进程
    /// </summary>
    [Service(ForegroundServiceType = Android.Content.PM.ForegroundService.TypeDataSync)]
    public class ForegroundService : Service
    {
        /// <summary>
        /// 通知ID - 用于标识前台服务的通知
        /// </summary>
        private const int NotificationId = 1001;
        
        /// <summary>
        /// 消息通知ID - 用于标识定时消息通知
        /// </summary>
        private const int MessageNotificationId = 1002;
        
        /// <summary>
        /// 通知渠道ID - Android 8.0及以上版本需要通知渠道
        /// </summary>
        private const string ChannelId = "ForegroundServiceChannel";
        
        /// <summary>
        /// 消息通知渠道ID
        /// </summary>
        private const string MessageChannelId = "MessageNotificationChannel";
        
        /// <summary>
        /// 定时器 - 用于每5秒发送一次通知
        /// </summary>
        private System.Timers.Timer? _messageTimer;
        
        /// <summary>
        /// 通知管理器
        /// </summary>
        private NotificationManager? _notificationManager;
        
        
        /// <summary>
        /// 当前服务实例
        /// </summary>
        private static ForegroundService? _currentInstance;

        /// <summary>
        /// 控制回调接口
        /// </summary>
        public static Action<bool> OnNotificationStateChanged;

        /// <summary>
        /// 日志管理器
        /// </summary>
        private LogManager _logManager = LogManager.Instance;
        
        /// <summary>
        /// 定时通知运行状态
        /// </summary>
        private bool _isNotificationRunning = false;
        
        /// <summary>
        /// 消息计数器
        /// </summary>
        private int _messageCount = 0;

        
        /// <summary>
        /// 服务创建时的回调方法
        /// 在这里进行服务的初始化工作
        /// </summary>
        public override void OnCreate()
        {
            base.OnCreate();
            _currentInstance = this;
            _notificationManager = (NotificationManager?)GetSystemService(NotificationService);
            
            CreateNotificationChannel();
            CreateMessageNotificationChannel();
            _logManager.LogService("OnCreate: 前台服务正在创建");
        }

        /// <summary>
        /// 服务启动命令处理方法
        /// 当通过StartService或StartForegroundService启动服务时会调用此方法
        /// </summary>
        /// <param name="intent">启动服务的Intent对象</param>
        /// <param name="flags">启动标志</param>
        /// <param name="startId">启动ID</param>
        /// <returns>服务重启策略</returns>
        public override StartCommandResult OnStartCommand(Intent? intent, StartCommandFlags flags, int startId)
        {
            _logManager.LogService("OnStartCommand: 前台服务启动命令执行");
            
            var notification = CreateNotification();
            StartForeground(NotificationId, notification);
            _logManager.LogService("OnStartCommand: 前台服务通知已创建并显示");
            
            // 在这里执行您的后台任务
            DoWork();
            _logManager.LogService("OnStartCommand: 后台工作任务已启动");
            
            return StartCommandResult.Sticky;
        }

        /// <summary>
        /// 绑定服务时的回调方法
        /// 由于这是一个前台服务，不需要绑定功能，返回null
        /// </summary>
        /// <param name="intent">绑定服务的Intent对象</param>
        /// <returns>服务绑定器，这里返回null表示不支持绑定</returns>
        public override IBinder? OnBind(Intent? intent)
        {
            return null;
        }
        /// <summary>
        /// 启动定时通知
        /// </summary>
        public static void StartTimedNotification()
        {
            var instance = GetServiceInstance();
            instance?.StartMessageTimer();
        }
        
        /// <summary>
        /// 停止定时通知
        /// </summary>
        public static void StopTimedNotification()
        {
            var instance = GetServiceInstance();
            instance?.StopMessageTimer();
        }
        
        /// <summary>
        /// 获取服务实例
        /// </summary>
        /// <returns>服务实例</returns>
        private static ForegroundService? GetServiceInstance()
        {
            return _currentInstance;
        }
        
        /// <summary>
        /// 创建通知渠道（Android 8.0及以上版本必需）
        /// 通知渠道用于对通知进行分类和管理
        /// </summary>
        private void CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channel = new NotificationChannel(
                    ChannelId,
                    "前台服务通知",
                    NotificationImportance.Low)
                {
                    Description = "用于显示前台服务状态的通知渠道"
                };

                _notificationManager?.CreateNotificationChannel(channel);
            }
        }
        
        /// <summary>
        /// 创建消息通知渠道
        /// </summary>
        private void CreateMessageNotificationChannel()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channel = new NotificationChannel(
                    MessageChannelId,
                    "定时消息通知",
                    NotificationImportance.Default)
                {
                    Description = "用于显示定时消息的通知渠道"
                };

                _notificationManager?.CreateNotificationChannel(channel);
            }
        }

        /// <summary>
        /// 创建前台服务通知
        /// 该通知将持续显示在状态栏中，告知用户服务正在运行
        /// </summary>
        /// <returns>构建好的通知对象</returns>
        private Notification CreateNotification()
        {
            var builder = new NotificationCompat.Builder(this, ChannelId)
                .SetContentTitle("前台服务运行中")
                .SetContentText("应用正在后台运行")
                .SetSmallIcon(Android.Resource.Drawable.IcMenuInfoDetails)
                .SetOngoing(true)
                .SetPriority(NotificationCompat.PriorityLow);

            return builder.Build();
        }

        /// <summary>
        /// 启动定时消息通知
        /// </summary>
        private void StartMessageTimer()
        {
            if (_isNotificationRunning)
            {
                _logManager.LogService("StartMessageTimer: 定时通知已在运行中");
                return;
            }
            
            _messageTimer = new System.Timers.Timer(5000); // 5秒间隔
            _messageTimer.Elapsed += OnTimerElapsed;
            _messageTimer.AutoReset = true;
            _messageTimer.Enabled = true;
            _isNotificationRunning = true;
            OnNotificationStateChanged?.Invoke(true);
            _logManager.LogService("StartMessageTimer: 定时器已配置，间隔5秒");
        }
        
        /// <summary>
        /// 停止定时消息通知
        /// </summary>
        private void StopMessageTimer()
        {
            if (!_isNotificationRunning)
            {
                _logManager.LogService("StopMessageTimer: 定时通知未运行");
                return;
            }
            
            _messageTimer?.Stop();
            _messageTimer?.Dispose();
            _messageTimer = null;
            _isNotificationRunning = false;
            OnNotificationStateChanged?.Invoke(false);
            _logManager.LogService("StopMessageTimer: 定时通知已停止");
        }
        
        /// <summary>
        /// 定时器触发事件 - 每5秒发送一次通知
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void OnTimerElapsed(object? sender, ElapsedEventArgs e)
        {
            _messageCount++;
            _logManager.LogService($"OnTimerElapsed: 定时器第{_messageCount}次触发");
            SendMessageNotification();
        }
        
        /// <summary>
        /// 发送消息通知
        /// </summary>
        private void SendMessageNotification()
        {
            var currentTime = DateTime.Now.ToString("HH:mm:ss");
            var notification = new NotificationCompat.Builder(this, MessageChannelId)
                .SetContentTitle($"定时消息 #{_messageCount}")
                .SetContentText($"发送时间: {currentTime}")
                .SetSmallIcon(Android.Resource.Drawable.IcDialogInfo)
                .SetAutoCancel(true)
                .SetPriority(NotificationCompat.PriorityDefault)
                .Build();

            _notificationManager?.Notify(MessageNotificationId + _messageCount, notification);
            
            _logManager.LogService($"SendMessageNotification: 发送第{_messageCount}条消息通知 - {currentTime}");
        }
        
        /// <summary>
        /// 执行后台工作任务
        /// 在这里添加您需要在后台持续执行的业务逻辑
        /// 例如：数据同步、状态监控、定时任务等
        /// </summary>
        private void DoWork()
        {
            // 在这里添加您要在前台服务中执行的任务
            // 例如：定期执行某些操作、监听网络状态等
            Task.Run(async () =>
            {
                int workCount = 0;
                while (true)
                {
                    // 模拟一些工作
                    await Task.Delay(10000);
                    workCount++;
                    _logManager.LogService($"DoWork: 后台任务执行第{workCount}次 - 服务正常运行");
                }
            });
        }

        /// <summary>
        /// 服务销毁时的回调方法
        /// 在这里进行资源清理和服务停止工作
        /// </summary>
        public override void OnDestroy()
        {
            _logManager.LogService("OnDestroy: 前台服务正在销毁");
            
            
            // 停止定时器
            StopMessageTimer();
            
            _currentInstance = null;
            _logManager.LogService("OnDestroy: 前台服务销毁完成");
            base.OnDestroy();
            StopForeground(true);
        }
    }
}